/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import parsePhoneNumber_ from './parsePhoneNumber_.js'

export default function parsePhoneNumber() {
	const { text, options, metadata } = normalizeArguments(arguments)
	return parsePhoneNumber_(text, options, metadata)
}

export function normalizeArguments(args)
{
	const [arg_1, arg_2, arg_3, arg_4] = Array.prototype.slice.call(args)

	let text
	let options
	let metadata

	// If the phone number is passed as a string.
	// `parsePhoneNumber('88005553535', ...)`.
	if (typeof arg_1 === 'string') {
		text = arg_1
	}
	else throw new TypeError('A text for parsing must be a string.')

	// If "default country" argument is being passed then move it to `options`.
	// `parsePhoneNumber('88005553535', 'RU', [options], metadata)`.
	if (!arg_2 || typeof arg_2 === 'string')
	{
		if (arg_4) {
			options = arg_3
			metadata = arg_4
		} else {
			options = undefined
			metadata = arg_3
		}

		if (arg_2) {
			options = { defaultCountry: arg_2, ...options }
		}
	}
	// `defaultCountry` is not passed.
	// Example: `parsePhoneNumber('+78005553535', [options], metadata)`.
	else if (isObject(arg_2))
	{
		if (arg_3) {
			options  = arg_2
			metadata = arg_3
		} else {
			metadata = arg_2
		}
	}
	else throw new Error(`Invalid second argument: ${arg_2}`)

	return {
		text,
		options,
		metadata
	}
}

// Otherwise istanbul would show this as "branch not covered".
/* istanbul ignore next */
const isObject = _ => typeof _ === 'object'